/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.servicecomb.exception;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.je.common.auth.impl.RealOrganizationUser;
import com.je.common.auth.impl.account.Account;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class CloudExceptionInfoStorage {

    public static MetaResourceService metaResourceService;

    private static final Logger logger = LoggerFactory.getLogger(CloudExceptionInfoStorage.class);

    public static final String tableCode="JE_CORE_EXCEPTIONLOG";

    private static List<String>  filterParameter = Lists.newArrayList(
            "param0"
    );
    static {
        if(metaResourceService==null){
            metaResourceService= SpringContextHolder.getBean(MetaResourceService.class);
        }
    }

    public static void saveExceptionLog(String url, Map<String,String[]> map, String message, String code, StackTraceElement[] stackTraceElements){
       DynaBean setting = metaResourceService.selectOneByNativeQuery("JE_CORE_SETTING",
                NativeQuery.build().eq("CODE","JE_SYS_LOGINFO"));
       if(setting!=null){
           String value = setting.getStr("VALUE");
           if(StringUtil.isEmpty(value)||(value.split(",").length==0)){
               return;
           }
           List<String> list = Arrays.asList(value.split(","));
           if(!list.contains("JE_SYS_EXCEPTIONLOG")){
                return;
           }
       }
        try{
            DynaBean dynaBean = new DynaBean();
            dynaBean.table(tableCode);
            dynaBean.setStr("EXCEPTIONLOG_URL",url);
            dynaBean.setStr("EXCEPTIONLOG_MESSAGE",message);
            dynaBean.setStr("EXCEPTIONLOG_CODE",code);
            dynaBean.setStr("EXCEPTIONLOG_STACKTRACE",getStackTraceInfo(stackTraceElements));
            dynaBean.set("EXCEPTIONLOG_PARAMETER",getParameter(map));
            dynaBean.put("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
            Account account = SecurityUserHolder.getCurrentAccount();
            if(account!=null){
                RealOrganizationUser realOrganizationUser = account.getRealUser();
                if (realOrganizationUser != null) {
                    dynaBean.put("SY_CREATEUSERID", realOrganizationUser.getId());
                    dynaBean.put("SY_CREATEUSERNAME", realOrganizationUser.getName());
                }
            }
            metaResourceService.insert(dynaBean);
        }catch (Exception e){
            logger.info("保存异常日志失败");
        }

    }

    private static Object getParameter(Map<String, String[]> map) {
        JSONObject jsonObject = new JSONObject();
        if(map!=null){
            for(Map.Entry<String, String[]> entry:map.entrySet()) {
                if(!filterParameter.contains(entry.getKey())){
                    jsonObject.put(entry.getKey(),entry.getValue()!=null? URLDecoder.decode(entry.getValue()[0]):"");
                }
            }
        }
        return JSON.toJSONString(jsonObject);
    }

    private static String getStackTraceInfo(StackTraceElement[] stackTraceElements) {
        StringBuilder  sb = new StringBuilder();
        for(StackTraceElement stackTraceElement:stackTraceElements){
            sb.append(stackTraceElement.toString());
            sb.append("\n");
        }
        return sb.toString();
    }

}
